<?php
namespace app\api\model;
use think\Exception;
use think\model;
use app\api\validate\UserTotal as UserTotalValidate;

class UserWithdrawalsModel extends model
{
	protected $table = 'ly_user_withdrawals';

	/**
	 * [draw 提现接口]
	 * @return [type] [description]
	 */
	public function draw(){
		//获取参数
		$post 		= input('post.');
		$token 		= input('post.token/s');
		$userArr	= explode(',',auth_code($token,'DECODE'));//uid,username
		$uid		= $userArr[0];//uid
		$username	= $userArr[1];//username

		$lang		= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型

		//查询用户类型——测试用户类型不允许提现
		$userType = model('users')->where('id',$uid)->value('user_type');
		if($userType == 3) return ['code' => 0, 'code_dec' => config($lang.'.lang')[41]];

		$userState = model('users')->where('id',$uid)->value('state');
		if($userState != 1) return ['code' => 0, 'code_dec' => config($lang.'.lang')[41]];

//		$drawtime = cache('C_DrawTime_'.$uid) ? cache('C_DrawTime_'.$uid) : time()-2;
//		//2秒
//		if(time()-$drawtime < 2) return ['code' => 0, 'code_dec' => config($lang.'.lang')[125]];

        //		cache('C_DrawTime_'.$uid,time()+2);
//		$dtime1 = mktime(10,0,0,date('m'),date('d'),date('Y'));
//		$dtime2 = mktime(17,0,0,date('m'),date('d'),date('Y'));
//		if(time()<$dtime1 || time()>$dtime2) return ['code' => 0, 'code_dec' => 'This time not allowed!'];

		//判断是否可以提现
		$withdrawals_state = model('Users')->where(array('id'=>$uid,'withdrawals_state'=>1))->count();

		if(!$withdrawals_state) return ['code' => 0, 'code_dec' => config($lang.'.lang')[143]];

		//低以50不能提现
		// $credit = model('users')->where('id',$uid)->value('credit');
		// if($credit<50) return ['code' => 0, 'code_dec' => config($lang.'.lang')[144]];

		//提现范围
		$wherew = [
			['uid' , '=' , $uid],
			['state','=',6],
		];
		$wherew2 = [
			['uid' , '=' , $uid],
			['state','=',1],
		];

        $log = array();

        model("api/UserLog")->clientlog($uid,"提现申请",$log);

//		$userwcount = model('UserWithdrawals')->whereOr([$wherew, $wherew2])->count();
//		$uservip = model('users')->where('id',$uid)->value('vip_level');
//		if($uservip == 1 && $userwcount >0){
//			return ['code' => 0, 'code_dec' => 'Ordinary members can only withdraw once'];
//		}
		$settingData = model('Setting')->where('id',1)->find();

		if(($post['draw_money'] < $settingData['min_w']) || ($post['draw_money'] > $settingData['max_w'])) return ['code' => 0, 'code_dec' => config($lang.'.lang')[145]];

		if(!isset($post['address']) || empty($post['address'])){
			return ['code' => 0, 'code_dec' =>config($lang.'.with')[0]];
		}
		if(!isset($post['credit_type']) || empty($post['credit_type']) || $post['credit_type']==1){
			return ['code' => 0, 'code_dec' => config($lang.'.with')[1]];
		}


        try{
            //用户余额
            $cbalance = model('UserTotal')->where('uid',$uid)->value('balance');
            //p($cbalance);
            if($cbalance<$post['draw_money']){
                return ['code' => 0, 'code_dec' => config($lang.'.task')[20]];
            }
//            $fee=db('rechange_type')->where(['id'=>$post['credit_type']])->value('fee');;//手续费
//            $tax=db('rechange_type')->where(['id'=>$post['credit_type']])->value('tax');//税率
            $fee = 0;
            $tax = 0;
            $real_price=($post['draw_money']-$fee) * $tax;
            $carry['uid']          = $uid;
            $carry['price']        = $post['draw_money'];
            $carry['real_price']        =$real_price;
            $carry['tax']        = $tax;
            $carry['address']        = $post['address'];
            $carry['credit_type']        = $post['credit_type'];
            $carry['time']         = time();
            $carry['order_number'] = trading_number();
            $carry['trade_number'] = trading_number();
            $carry['lang']         = $lang;
            // $carry['phone']        = $post['phone'];
            // $carry['email']        = $post['email'];
            // $carry['ifsc']         = $post['ifsc'];
            $carry['remarks']      = config($lang.'.with')[2];

            $isinsert = $this->insert($carry);

            if(!$isinsert){
                $data['code'] 		= 0;
                $data['code_dec']	= config($lang.'.with')[3];
                return $data;
            }

            //用户余额
            $cbalance = model('UserTotal')->where('uid',$uid)->value('balance');
            //更新余额
            db('UserTotal')->where('uid',$uid)->Dec('total_balance',$post['draw_money']);

            $map[] = array('uid','=',$uid);
            $map[] = array('balance','>=',$post['draw_money']);
            $isupdata = model('UserTotal')->where($map)->setDec('balance',$post['draw_money']);
            if(!$isupdata) return ['code' => 0, 'code_dec' => config($lang.'.lang')[41]];

            //添加流水
            $financial_data['uid']					=	$uid;
            $financial_data['username']				=	$username;
            $financial_data['sid']					=	$uid;
            $financial_data['state']				=	3;
            $financial_data['order_number']			=	$carry['order_number'];
            $financial_data['trade_number']			=	$carry['trade_number'];
            $financial_data['trade_type']			=	2;
            $financial_data['trade_before_balance']	=	$cbalance;
            $financial_data['trade_amount']			=	$post['draw_money'];
            $financial_data['account_balance']		=	$cbalance - $post['draw_money'];
            $financial_data['remarks']				=	config($lang.'.lang')[184];
            $financial_data['vip_level']			=	model('Users')->where('id',$uid)->value('vip_level');
            $financial_data['isdaily']				=	2;
            $financial_data['credit_type']				=	$carry['credit_type'];
            $financial_data['tax']				=	$carry['tax'];
            $financial_data['real_trade_amount']				=	$carry['real_price'];

            $insert = model('TradeDetails')->tradeDetails($financial_data);

            if(!$insert) return ['code' => 0, 'code_dec' => config($lang.'.lang')[41]];

            return ['code'=>1,'code_dec'=>config($lang.'.lang2')[3]];
        }catch (Exception $e){
            $log['异常信息'] = $e->getMessage();
            model("api/UserLog")->clientlog($uid,"充值异常",$log);
            return ['code'=>0, 'code_dec'=>'recharge exception'];
        }
    }

	/**
	 * 提现记录
	 */
	public function getUserWithdrawalsList(){
		//获取参数
		$token 		= input('post.token/s');
		$userArr	= explode(',',auth_code($token,'DECODE'));//uid,username
		$uid		= $userArr[0];//uid
		$username 	= $userArr[1];//username
		$lang		= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		$param 		= input('post.');

		if(!$uid){
			$data['code'] = 0;
			return $data;
		}

		$where[] = array('uid','=',$uid);

		//状态
		if (isset($param['state']) and $param['state']) {
			$where[] = array('state','=',$param['state']);
		}
		/*//开始时间
		if (isset($param['search_time_s']) and $param['search_time_s']) {
			$where[] = array('time','>=',strtotime($param['search_time_s']));
		} else {
			$where[] = array('time','>=',mktime(0,0,0,date('m'),date('d'),date('Y')));
		}
		//结束时间
		if (isset($param['search_time_e']) and $param['search_time_e']) {
			$where[] = array('time','<=',strtotime($param['search_time_e']));
		} else {
			$where[] = array('time','<=',mktime(23,59,59,date('m'),date('d'),date('Y')));
		}*/

		//分页
		//总记录数
		$count = $this->where($where)->count();
		if(!$count) return ['code' => 0, 'code_dec' => config($lang.'.lang')[45]];

		//每页记录数
		$pageSize	= (isset($param['pagesize']) and $param['pagesize']) ? $param['pagesize'] : 10;
		//当前页
		$page		= (isset($param['page']) and $param['page']) ? $param['page'] : 1;

		$dataAll = $this->where($where)
				->order(['time'=>'desc','id'=>'desc'])
				->paginate($pageSize)
		        ->toArray();


        $dataAll['code'] 				= 1;
        $dataAll['data_total_nums'] 	= $dataAll['total'];
        $dataAll['data_current_page'] 	= $dataAll['current_page'];

        $list=[];

        $withdrawalsStates = config('custom.'.$lang.'withdrawalsState');

		//数组重组赋值
		foreach ($dataAll['data'] as $key => &$value) {
			// $rmoney = 0;
			// if($value['state'] == 1 || $value['state'] == 6)
			// {
			// 	$rmoney = $value['price'];
			// }
			$list[$key]['dan'] 			= $value['order_number'];
			$list[$key]['adddate'] 		= date('Y-m-d H:i:s',$value['time']);
			$list[$key]['address'] 			= $value['address'];
			$list[$key]['money'] 		= $value['price'];
			$list[$key]['real_price'] 		= $value['real_price'];
			$list[$key]['fee'] 		= $value['fee'];
			$list[$key]['tax'] 		= $value['tax'];
			//$list[$key]['rmoney'] 		= $rmoney;//($value['state'] == 1) ? $value['price'] : 0;
            $state = $value['state'];
            if (isset($withdrawalsStates[$state])){
                $state = $withdrawalsStates[$state];
            }
			$list[$key]['status_desc'] 	= $state;
			//$list[$key]['remark'] 		= $value['remarks'];
			$list[$key]['typedes'] 		= config($lang.'.lang')[185];
		}
		$dataAll['data']=$list;

		return $dataAll;
	}


	/**
	 * 团队提现
	 */
	public function teamWithdrawals(){
		//获取参数并过滤
		$param 				= input('param.');
		$param['user_id'] 	= input('param.user_id/d');
		$lang		= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		if(!$param['user_id']){
			$data['code'] = 0;
			return $data;
		}

		$where[] = array('user_team.uid','=',$param['user_id']);
		$where[] = array('user_team.team','neq',$param['user_id']);

		//用户名搜索
		if (isset($param['username']) and $param['username']) {
			$where[] = array('username','=',$param['username']);
		}
		//状态
		if (isset($param['state']) and $param['state']) {
			$where[] = array('ly_user_withdrawals.state','=',$param['state']);
		}
		//开始时间
		if (isset($param['search_time_s']) and $param['search_time_s']) {
			$where[] = array('time','>=',strtotime($param['search_time_s']));
		} else {
			$where[] = array('time','>=',mktime(0,0,0,date('m'),date('d'),date('Y')));
		}
		//结束时间
		if (isset($param['search_time_e']) and $param['search_time_e']) {
			$where[] = array('time','<=',strtotime($param['search_time_e']));
		} else {
			$where[] = array('time','<=',mktime(23,59,59,date('m'),date('d'),date('Y')));
		}

		//分页
		//总记录数
		$count = $this->join('users','ly_user_withdrawals.uid = users.id')->join('user_team','ly_user_withdrawals.uid = user_team.team')->where($where)->count();
		//每页记录数
		$pageSize = (isset($param['page_size']) and $param['page_size']) ? $param['page_size'] : 10;
		//当前页
		$pageNo = (isset($param['page_no']) and $param['page_no']) ? $param['page_no'] : 1;
		//总页数
		$pageTotal = ceil($count / $pageSize); //当前页数大于最后页数，取最后
		//偏移量
		$limitOffset = ($pageNo - 1) * $pageSize;

		//数据
		$dataArray = $this->field('ly_user_withdrawals.*,users.username')
							->join('users','ly_user_withdrawals.uid = users.id')
							->join('user_team','ly_user_withdrawals.uid = user_team.team')
							->where($where)
							->order('time','desc')
							->limit($limitOffset, $pageSize)
							->select();

		if (!$dataArray) {
			$data['code'] = 0;
			return $data;
		}

		//获取成功
		$data['code'] 				= 1;
		$data['data_total_nums'] 	= $count;
		$data['data_total_page'] 	= $pageTotal;
		$data['data_current_page'] 	= $pageNo;
		$decimalPlace = config('api.decimalPlace');
		foreach($dataArray as $key => $value){
			$rmoney = 0;
			if($value['state'] == 1 || $value['state'] == 6)
			{
				$rmoney = $value['price'];
			}
			$value['fee'] = round($value['fee'],$decimalPlace);
			$value['price'] = round($value['price'],$decimalPlace);
			$rmoney = round($rmoney,$decimalPlace);
			$data['info'][$key]['dan']                  =   $value['order_number'];
			$data['info'][$key]['adddate']              =   date('Y-m-d H:i:s',$value['time']);
			$data['info'][$key]['username']             =   $value['username'];
			$data['info'][$key]['real_name']            =   mb_substr($value['card_name'],0,1,"utf-8").'**';
			$data['info'][$key]['fee']             	    =   $value['fee'];
			$data['info'][$key]['bank_no_tail']         =   substr_replace($value['card_number'],'*******************',0,-4);
			$data['info'][$key]['money']                =   $value['price'];
			$data['info'][$key]['rmoney']				=	$rmoney;//($value['state'] == 1) ? $value['price'] : 0;
			$data['info'][$key]['status_desc']          =   config('custom.withdrawalsState')[$value['state']];
			$data['info'][$key]['remarks']				=	$value['remarks'];
		}

		return $data;
	}
}
